window.addEventListener('load', function () {
    //获取分类列表，渲染页面
    let tbody = document.querySelector('.layui-table>tbody')
    function init() {
        obj.url = '/my/article/cates'
        obj.type = 'GET'
        obj.success = function (res) {
            if (res.status === 0)
                render(res.data)
        }
        function render(data) {
            let str = template('tpl-table', { data: data })
            tbody.innerHTML = str
        }
        myAxios(obj)
    }
    init()
    // 添加分类
    let index
    btnAddCate.onclick = function () {
        let str = template('dialog-add', {})
        index = layer.open({
            type: 1,
            content: str
        })
    }
    //编辑分类
    tbody.addEventListener('click', function (e) {
        if (e.target.innerText === '编辑') {
            let data = {
                "Id": e.target.dataset.id,
                "name": e.target.parentNode.parentNode.children[0].innerText,
                "alias": e.target.parentNode.parentNode.children[1].innerText
            }
            let str = template('dialog-edit', data)
            index = layer.open({
                type: 1,
                content: str
            })
        }
    })
    layui.use('form', function () {
        var form = layui.form;
        //监听提交
        let cb = function (res) {
            if (res.status === 0) {
                layer.close(index)
                layer.msg(res.message, { time: 1000 })
                init()
            }
        }
        form.on('submit(formDemo)', function (data) {
            obj.type = 'POST'
            obj.url = '/my/article/addcates'
            obj.data = data.field
            obj.success = cb
            myAxios(obj)
            return false;
        });
        form.on('submit(formEdit)', function (data) {
            obj.url = '/my/article/updatecate'
            obj.type = 'post'
            obj.data = data.field
            obj.success = cb
            myAxios(obj)
            return false;
        });
        form.verify({
            morethan2: [
                /^[\S]{2,}$/
                , '最少包含2个字符'
            ]
        });
    });
    //删除分类
    tbody.addEventListener('click', function (e) {
        if (e.target.innerText === '删除') {
            layer.confirm('确定删除？', { icon: 3, title: '提示' }, function (index) {
                deleArticle(e)
                layer.close(index);
            });
        }
    })
    function deleArticle(e) {
        let id = e.target.dataset.id
        obj.url = '/my/article/deletecate/' + id
        obj.type = 'GET'
        obj.success = function (res) {
            layer.msg(res.message, {
                icon: 1,
                time: 2000 //2秒关闭（如果不配置，默认是3秒）
            }, function () {
                if (res.status === 0)
                    window.location.reload()
            });
        }
        myAxios(obj)
    }
})
